package com.koron.ticket.work.workflow.service;

import cn.hutool.core.collection.CollUtil;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.workflow.util.TextUtil;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.ticket.utils.StringUtils;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.bean.WorkFlowQuery;
import com.koron.ticket.work.workflow.mapper.WorkFlowMapper;
import com.koron.ticket.work.workticket.service.WorkTicketService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WorkFlowService {

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

//    private static Date currentTime = new Date();

    @Autowired
    private WorkTicketService workticketservice;

    @TaskAnnotation("updateList")
    public Response updateList(SessionFactory factory, List<WorkFlow> workFlowList) {
        for (WorkFlow workFlow : workFlowList) {
            this.update(factory, workFlow);
        }
        return Response.success("所有签名已更新");
    }

    @TaskAnnotation("batchDeleteById")
    public Response batchDeleteById(SessionFactory factory, List<String> idList) {
        for (String id : idList) {
            this.deleteById(factory, id);
        }
        return Response.success("批量删除成功");
    }

    public void insert(SessionFactory factory, WorkFlow workFlow, Integer status) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);

        workFlow.setId(CodeTools.getCode32());
        workFlow.setStatus(status);
        workFlow.setCreateUserId(getCurrUser().getId());
        workFlow.setCreateUserName(getCurrUser().getName());
        workFlow.setCreateTime(new Date());
        workFlowMapper.insert(workFlow);
    }

    public void insert(SessionFactory factory, WorkFlow workFlow) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);

        workFlow.setId(CodeTools.getCode32());
        workFlow.setCreateUserId(getCurrUser().getId());
        workFlow.setCreateUserName(getCurrUser().getName());
        workFlow.setCreateTime(new Date());
        workFlowMapper.insert(workFlow);
    }

    public void batchInsert(SessionFactory factory, List<WorkFlow> list) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        list.stream().forEach(l->{
            l.setId(CodeTools.getCode32());
            l.setCreateUserId(getCurrUser().getId());
            l.setCreateUserName(getCurrUser().getName());
            l.setCreateTime(new Date());
        });
        workFlowMapper.batchInsert(list);
    }

    public void update(SessionFactory factory, WorkFlow workFlow) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        workticketservice.updateUpdateTime(factory, workFlow.getWorkTicketId());//  更新票据最后操作时间
        workFlowMapper.update(workFlow);
    }

    public void save(SessionFactory factory, WorkFlow workFlow) {
        // 1. 保存签名数据
        if (StringUtils.isEmpty(workFlow.getId())) {
            this.insert(factory, workFlow);
        } else {
            this.update(factory, workFlow);
        }
    }

    public void deleteById(SessionFactory factory, String id) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        workFlowMapper.deleteById(id);
    }

    public List<WorkFlow> getList(SessionFactory factory, WorkFlowQuery workFlowQuery) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        return workFlowMapper.getList(workFlowQuery);
    }

    public WorkFlow getSingle(SessionFactory factory, WorkFlowQuery workFlowQuery) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        return workFlowMapper.getSingle(workFlowQuery);
    }

    public List<WorkFlow> queryByTicketId(SessionFactory factory, String ticketId) {
        WorkFlowQuery workFlowQuery = new WorkFlowQuery();
        workFlowQuery.setWorkTicketId(ticketId);
        List<WorkFlow> list = getList(factory, workFlowQuery);
        return list;
    }

    public void insertByMap(SessionFactory factory, Map<String, String> workFlowMap) throws ParseException {
        // 由于id已经被占用，所以前端用workFlowId来代替
        String id = workFlowMap.get("workFlowId");
        String workTicketId = workFlowMap.get("workTicketId");
        String type = workFlowMap.get("type");
        String account = workFlowMap.get("account");
        String name = workFlowMap.get("name");
        String phone = workFlowMap.get("phone");
        Integer status = Integer.valueOf(workFlowMap.get("status"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 待许可/工作待终结/工作票待终结中签名时间可能为空
        String operationTimeString = workFlowMap.get("operationTime");
        Date operationTime = new Date();
        if (StringUtils.isNotEmpty(operationTimeString)) {
            operationTime = simpleDateFormat.parse(operationTimeString);
        }
        // 20211109: 兼容前端传空数据
        if (StringUtils.isEmpty(id) && StringUtils.isNotEmpty(account)) {
            WorkFlow workFlow = new WorkFlow();
            workFlow.setWorkTicketId(workTicketId);
            workFlow.setType(type);
            workFlow.setAccount(account);
            workFlow.setName(name);
            workFlow.setPhone(phone);
            workFlow.setDeleteFlag(0);
            workFlow.setOperationTime(operationTime);
            this.insert(factory, workFlow, status);
        } else {
            WorkFlowQuery workFlowQuery = new WorkFlowQuery();
            workFlowQuery.setId(id);
            WorkFlow workFlow = this.getSingle(factory, workFlowQuery);
            workFlow.setOperationTime(operationTime);
            this.update(factory, workFlow);
        }
    }

    public Response insertByStringMap(SessionFactory factory, String workFlowListString, Integer status) throws ParseException {
        String[] workFlowStringList = workFlowListString.split("},\\{");
        Integer number = workFlowStringList.length;

        // 1. 如果只有一条签名数据
        if (number == 1) {
            // 1.1 将数据两边的“[]”去除
            String mapString = workFlowStringList[0].substring(1, workFlowStringList[0].length() - 1);
            // 1.2 转换成map
            Map<String, String> map = TextUtil.toMapFromString(mapString);
            // 1.3 插入数据
            this.insertByMap(factory, map);
        } //2. 如果只有两条签名数据
        else if (number == 2) {
            // 2.1 将第一条数据的第一个字符去除
            String firstStringMap = workFlowStringList[0].substring(1);
            // 2.2 补全末尾的“}”，并转换成map
            Map<String, String> firstMap = TextUtil.toMapFromString(firstStringMap + "}");
            // 2.3 将第二条数据的最后一个字符去除
            String secondStringMap = workFlowStringList[1].substring(0, workFlowStringList[1].length() - 1);
            // 2.4 补全开头的“{”，并转换成map
            Map<String, String> secondMap = TextUtil.toMapFromString("{" + secondStringMap);
            // 2.5 将两个数据插入
            this.insertByMap(factory, firstMap);
            this.insertByMap(factory, secondMap);
        } // 3. 如果数据大于3条
        else if (number >= 3) {
            // 3.1 将第一条数据的第一个字符去除
            String firstStringMap = workFlowStringList[0].substring(1);
            // 3.2 补全末尾的“}”，并转换成map
            Map<String, String> firstMap = TextUtil.toMapFromString(firstStringMap + "}");
            // 3.3 插入第一条数据
            this.insertByMap(factory, firstMap);
            // 3.4 对所有的中间数据进行统一操作
            for (int i = 1; i < number - 1; i++) {
                Map<String, String> midMap = TextUtil.toMapFromString("{" + workFlowStringList[i] + "}");
                this.insertByMap(factory, midMap);
            }
            // 3.5 将第最后一条数据的最后一个字符去除(复制粘贴害人)
            String finalStringMap = workFlowStringList[number-1].substring(0, workFlowStringList[number-1].length() - 1);
            // 3.6 补全开头的“{”，并转换成map
            Map<String, String> finalMap = TextUtil.toMapFromString("{" + finalStringMap);
            // 3.7 插入最后一条数据
            this.insertByMap(factory, finalMap);
        }
        return Response.success();
    }

    public void deleteByWorkTicketId(SessionFactory factory, String workTicketId, Integer status) {
        WorkFlowMapper workFlowMapper = factory.getMapper(WorkFlowMapper.class);
        workFlowMapper.deleteByWorkTicketIdAndStatus(workTicketId, status);
    }
}
